<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>设置</title>
    <link rel="stylesheet" href="../common/style/reset.css" />
    <style>
      .search-box{
        border: 1px solid #6722ff;
        height: 25px;
        border-radius: 12.5px;
      }

      .search-box input{
        border: none;
        outline: none;
        height: 100%;
        width: 100%;
        background-color: transparent;
        padding: 0 10px;
        color: #777980;
      }

      .city-list{
        padding: 5px;
      }
    </style>
  </head>
  <body>
    <tab-win>
      <div class="search-box">
        <input type="text" placeholder="输入城市名称">
      </div>
      <div class="city-list">

      </div>
    </tab-win>
  </body>
  <script type="module">
    import TabWin from "../components/Window.js";
    customElements.define("tab-win", TabWin);

    const searchEl = document.querySelector('.search-box input')
    const cityListEl = document.querySelector('.city-list')

    const getCityList = async (value) => {
      let res = await fetch(`https://geoapi.qweather.com/v2/city/lookup?key=52333e1e98e0489cb4d65a6973051a95&location=${value}`)
      let data = await res.json()
      if(data.code === '200'){
        return data.location
      }else{
        // alert('网络错误')
        return null
      }
    }

    searchEl.onchange = async function (e){
      
      cityListEl.innerHTML = '';
      if(!e.target.value)return;
      let data = await getCityList(e.target.value);
      data && data.forEach(item=>{
        let list = document.createElement('div')
        list.innerText = item.name
        list.setAttribute('location-id', item.id)
        list.setAttribute('location-city', item.name)
        list.onclick = function (e){
          let locationId = e.target.getAttribute('location-id')
          let city = e.target.getAttribute('location-city')
          window.toParentPage({locationId, city})
        }
        cityListEl.appendChild(list)
      })
    }
    
    
  </script>
</html>
